import { Descriptions, Empty, Modal } from 'antd'
import './TimeLineScroll.less'
import React, { useRef, useEffect, useState, useCallback } from 'react'
import LeftIcon from './left_icon.png'
import RightIcon from './right_icon.png'
// 组件属性接口定义
interface IProps {
  modalInstance: any // 模态框实例，用于控制模态框的显示和隐藏
  // current?: number // 当前所处的阶段索引，用于高亮显示当前状态
}
const TimeLineScroll: React.FC<IProps> = ({ modalInstance }) => {
  const timelineContainerRef = useRef<HTMLDivElement>(null) // 时间线容器的引用，用于获取容器宽度
  const timelineWrapperRef = useRef<HTMLDivElement>(null) // 时间线内容包裹层的引用，用于滚动
  const timelineScrollAreaRef = useRef<HTMLDivElement>(null) // 新增：可滚动区域的引用
  const [showLeftFade, setShowLeftFade] = useState(false) // 控制是否显示左侧
  const [showRightFade, setShowRightFade] = useState(false) // 控制是否显示右侧
  const [timelineLineWidth, setTimelineLineWidth] = useState(0) // 时间线长度状态

  // 检查是否需要显示滚动按钮
  const checkScrollStatus = () => {
    if (timelineScrollAreaRef.current && timelineWrapperRef.current) {
      const { scrollWidth, clientWidth, scrollLeft } = timelineScrollAreaRef.current
      const isAtRight = Math.abs(scrollLeft + clientWidth - scrollWidth) < 1 // 添加1px的容差
      // 根据滚动位置判断是否到头了
      setShowLeftFade(scrollLeft > 0)
      setShowRightFade(!isAtRight)
      // 计算时间线长度
      setTimelineLineWidth(timelineWrapperRef.current.scrollWidth)
    }
  }

  // 滚动到指定位置
  const scrollTo = useCallback((scrollOffset: number) => {
    if (timelineScrollAreaRef.current) {
      // 使用 timelineScrollAreaRef
      timelineScrollAreaRef.current.scrollBy({
        left: scrollOffset,
        behavior: 'smooth',
      })
    }
  }, [])
  useEffect(() => {
    if (modalInstance.open && modalInstance?.currentRecord?.timelineData?.length > 0) {
      const timer = setTimeout(() => {
        checkScrollStatus()
      }, 100)
      return () => clearTimeout(timer)
    }
  }, [modalInstance.open, modalInstance?.currentRecord?.timelineData?.length, checkScrollStatus])

  // 监听容器宽度变化和滚动事件
  useEffect(() => {
    if (modalInstance.open) {
      console.log(123123123)

      timelineScrollAreaRef.current?.addEventListener('scroll', checkScrollStatus) // 使用 timelineScrollAreaRef
      return () => {
        timelineScrollAreaRef.current?.removeEventListener('scroll', checkScrollStatus) // 使用 timelineScrollAreaRef
      }
    }
  }, [modalInstance.open, modalInstance?.currentRecord?.timelineData?.length, checkScrollStatus])

  // 渲染组件
  return (
    <Modal
      width={1200}
      title="物流状态查询"
      footer={null}
      open={modalInstance.open}
      onCancel={modalInstance.closeModal}
      confirmLoading={modalInstance.confirmLoading}
    >
      <div>
        <Descriptions column={{ xxl: 4, xl: 3, lg: 3, md: 2, sm: 1, xs: 1 }} layout="vertical">
          <Descriptions.Item label="物流需求单">
            {modalInstance?.currentRecord?.transportationOrderCode || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="运单号">{modalInstance?.currentRecord?.wayBillNo || '-'}</Descriptions.Item>
          <Descriptions.Item label="运输方式">{modalInstance?.currentRecord?.businessType || '-'}</Descriptions.Item>
        </Descriptions>
      </div>
      <div className="timeline-container" ref={timelineContainerRef}>
        {modalInstance?.currentRecord?.timelineData?.length > 0 ? (
          <div className={`timeline-scroll-area show-scroll-buttons`} ref={timelineScrollAreaRef}>
            <div className="timeline-line" style={{ width: `${timelineLineWidth}px` }}></div>
            <div className="timeline-wrapper" ref={timelineWrapperRef}>
              {modalInstance?.currentRecord?.timelineData?.map((event: any, index: number) => (
                <div key={index} className="timeline-item">
                  <div
                    className={`timeline-dot ${
                      index === modalInstance?.currentRecord?.timelineData?.length - 1 ? 'active' : ''
                    }`}
                  ></div>
                  <div
                    className={`timeline-card-container ${
                      index === modalInstance?.currentRecord?.timelineData?.length - 1 ? 'active' : ''
                    }`}
                  >
                    <div className="timeline-card">
                      <div className="timeline-card-header">
                        <span className="title">{event?.transportStatus}</span>
                        {/* <span className="datetime-header">{event?.occurrenceTime}</span> */}
                      </div>
                      <div className="timeline-card-details">
                        <div>
                          <span>物流状态：</span>
                          <span>{event?.transportStatus}</span>
                        </div>
                        <div>
                          <span>时间节点：</span>
                          <span>{event?.occurrenceTime}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
        )}
      </div>

      {modalInstance?.currentRecord?.timelineData?.length > 0 ? (
        <div className="scroll-buttons-timeline">
          <button onClick={() => scrollTo(-300)} disabled={!showLeftFade}>
            <img src={LeftIcon} alt="" />
          </button>
          <button onClick={() => scrollTo(300)} disabled={!showRightFade}>
            <img src={RightIcon} alt="" />
          </button>
        </div>
      ) : null}
    </Modal>
  )
}

export default TimeLineScroll
